package com.zy.openchat.core.manager;

import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.zy.openchat.core.model.message.Draft;

public class ChatDraftManager {
    private volatile static ChatDraftManager redpackManaer;

    private final String SPU_KEY = "chatDrafts";

    private final String SPU_PRE_KEY = "chatDrafts_";

    private ChatDraftManager() {
    }

    public static ChatDraftManager getInstance() {
        if (redpackManaer == null) {
            synchronized (ChatDraftManager.class) {
                if (redpackManaer == null) {
                    redpackManaer = new ChatDraftManager();
                }
            }
        }
        return redpackManaer;
    }

    public String getChatDraft(long chatId){
        return SPUtils.getInstance().getString(getChatSPUKey(chatId),"");
    }

    public String getChatDraftContent(long chatId){
        Draft draft = null;
        String draftStr = SPUtils.getInstance().getString(getChatSPUKey(chatId),"");
        if(!TextUtils.isEmpty(draftStr)){
            draft = Draft.fromDraftJson(draftStr);
        }
        if(draft!=null){
            return draft.getContent();
        }
        return null;
    }


    public void saveDraft(long chatId,String draft){
        String spuChatIds = SPUtils.getInstance().getString(SPU_KEY,"");
        if(!TextUtils.isEmpty(spuChatIds)){
            spuChatIds = spuChatIds+":"+chatId;
        }else{
            spuChatIds = ""+spuChatIds;
        }
        SPUtils.getInstance().put(SPU_KEY,spuChatIds);
        SPUtils.getInstance().put(getChatSPUKey(chatId),draft);
    }

    private String getChatSPUKey(long chatId){
        return getChatSPUKey(String.valueOf(chatId));
    }

    private String getChatSPUKey(String chatId){
        return String.format("%s%s",SPU_PRE_KEY,chatId);
    }

    public void clean(){
        String spuChatIds = SPUtils.getInstance().getString(SPU_KEY,"");
        if(!TextUtils.isEmpty(spuChatIds)){
            String[] array = spuChatIds.split(":");
            if(array!=null&&array.length>0){
                for(String id:array){
                    SPUtils.getInstance().put(getChatSPUKey(id),"");
                }
            }
        }
        SPUtils.getInstance().put(SPU_KEY,"");
    }
}
